import { App } from 'vue'
import XtxSkeleton from './skeleton/index.vue'
import XtxCarousel from './carousel/index.vue'
import XtxMore from './more/index.vue'
import { useIntersectionObserver } from '@vueuse/core'
import defaultImg from '@/assets/images/200.png'
import XtxBread from './bread/index.vue'
import XtxBreadItem from './bread/item.vue'
import XtxCity from './city/index.vue'
import XtxNumbox from './numbox/index.vue'
import XtxButton from './button/index.vue'
import XtxCheckbox from './checkbox/index.vue'

export default {
  install(app: App) {
    // 自动执行
    // 全局注册组件
    app.component(XtxSkeleton.name, XtxSkeleton)
    app.component(XtxCarousel.name, XtxCarousel)
    app.component(XtxMore.name, XtxMore)
    app.component(XtxBread.name, XtxBread)
    app.component(XtxBreadItem.name, XtxBreadItem)
    app.component(XtxCity.name, XtxCity)
    app.component(XtxNumbox.name, XtxNumbox)
    app.component(XtxButton.name, XtxButton)
    app.component(XtxCheckbox.name, XtxCheckbox)

    // 全局注册组件
    // 参数1: 指令名
    // 参数2: 配置项
    app.directive('lazy', {
      // Vue2: 当绑定的元素插入到 DOM 中时执行, inserted
      // inserted(el, binding) {}
      // Vue3: 改为了 mounted
      mounted(el, binding) {
        // el: 当前指令绑定的 DOM 元素
        // console.log(el, binding)
        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            stop()
            el.src = binding.value
          }
        })

        // 如果图片加载失败，显示默认的图片
        el.onerror = () => {
          el.src = defaultImg
        }
      }
    })
  }
}